<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="车型" prop="carType">
        <el-input clearable v-model="queryParams.carType"/>
      </el-form-item>
      <el-form-item label="车牌" prop="licensePlate">
        <el-input clearable v-model="queryParams.licensePlate"/>
      </el-form-item>
      <el-form-item label="门店" prop="storeId">
        <el-select
          v-model="queryParams.storeId"
          placeholder="请选择门店"
          clearable
          filterable
          class="!w-150px"
        >
          <el-option
            v-for="dict in storeList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="付款时间" prop="payDate">
        <el-date-picker
          v-model="queryParams.payDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="收款状态" prop="payStatus">
        <el-select
          v-model="queryParams.payStatus"
          placeholder="请选择收款状态"
          clearable
          class="!w-240px"
        >
          <el-option label="未付款" value="1"/>
          <el-option label="部分付款" value="4"/>
          <el-option label="已付款" value="3"/>
        </el-select>
      </el-form-item>

      <el-form-item label="对账状态" prop="checkStatus">
        <el-select
          v-model="queryParams.checkStatus"
          placeholder="请选择收款状态"
          clearable
          class="!w-240px"
        >
          <el-option label="已对账" value="3"/>
          <el-option label="未对账" value="1"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>

        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['dispatch:payment:create']"
          size="small"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['dispatch:payment:export']"
          size="small"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
      </el-form-item>
    </el-form>
    <el-row class="mt-15px">
      <el-col>
        <el-button @click="handleBatchlPay" type="primary">批量确认付款</el-button>
        <el-button @click="handleBatchCancelPay" type="danger">批量撤销付款</el-button>
        <el-button @click="handleBatchReject" type="danger">批量驳回</el-button>
        <el-button @click="handleBatchReconciliation" type="primary">批量对账</el-button>
        <el-button @click="handleBatchCancelReconciliation" type="danger">批量撤销对账</el-button>
      </el-col>

    </el-row>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" ref="multipleTableRef" :summary-method="getSummaries" show-summary
              @selection-change="handleSelectionChange"
              border :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!--      <el-table-column label="订单编号" align="center" prop="id" />-->
      <el-table-column type="selection" fixed="left" width="40"/>
      <el-table-column label="操作" min-width="60" fixed="left" align="center" prop="payStatus">
        <template #default="scope">
          <el-popover :visible="popoverVisible == scope.row.id" placement="top" :width="100">

            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="primary"
                  @click="handlePay(scope.row)"
                  v-if="scope.row.unpaidAmount>0"
                  v-hasPermi="['dispatch:payment:update']"
                >
                  确认付款
                </el-button>
              </el-col>
            </el-row>

            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  style="margin: 0"
                  type="warning"
                  @click="cancelPay(scope.row.id)"
                  v-hasPermi="['dispatch:payment:update']"
                  v-if="scope.row.payStatus != 1"
                >
                  撤销付款
                </el-button>
              </el-col>
            </el-row>

            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="danger"
                  @click="handleDelete(scope.row.id)"
                  v-hasPermi="['dispatch:payment:delete']"
                  v-if="scope.row.payStatus ==1"
                >
                  驳回
                </el-button>
              </el-col>
            </el-row>

            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="danger"
                  @click="handleCancelCheck(scope.row.id)"
                  v-hasPermi="['dispatch:payment:delete']"
                  v-if="scope.row.checkStatus ==3"
                >
                  取消对账
                </el-button>
              </el-col>
            </el-row>

            <div class="popoverCloseBtn" @click="closePopover()">关闭</div>
            <template #reference>
              <img src="@/assets/imgs/more_edit.png" class="linkBtn"
                   @click="handleRightClick(scope.row.id)"
                   @contextmenu.prevent="handleRightClick(scope.row.id)"/>
            </template>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="门店" min-width="120" prop="storeName"/>
      <el-table-column label="车型" min-width="150" prop="carType"/>
      <el-table-column label="车牌" min-width="120" prop="licensePlate"/>
      <el-table-column label="付款状态" min-width="90" align="center" prop="payStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_PAY_STATUS" :value="scope.row.payStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="付款金额" align="center" min-width="130" prop="dispatchPrice"/>
      <el-table-column label="优惠金额" min-width="90" prop="discountPrice"/>

      <el-table-column label="付款账户" min-width="90" prop="payAccount"/>
      <el-table-column label="付款方式" min-width="90" align="center" prop="payMode">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_SETTLE_TYPE" :value="scope.row.payMode"/>
        </template>
      </el-table-column>
      <el-table-column
        label="付款时间"
        align="center"
        prop="payDate"
        :formatter="dateFormatter"
        width="100px"
      />

      <el-table-column label="已付金额" min-width="130" align="center" prop="paidAmount"/>
      <el-table-column label="未付金额" min-width="130" align="center" prop="unpaidAmount"/>
      <el-table-column label="对账状态" min-width="90" align="center" prop="checkStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.DISPATCH_CHECK_STATUS" :value="scope.row.checkStatus"/>
        </template>
      </el-table-column>
      <el-table-column
        label="对账时间"
        align="center"
        prop="checkDate"
        :formatter="dateFormatter"
        width="100px"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="100px"
      />
      <el-table-column label="订单编号" min-width="160" align="center" prop="no"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <!--      <el-table-column label="开启状态" align="center" prop="status" />-->
      <!--      <el-table-column label="排序" align="center" prop="sort" />-->
      <!--      <el-table-column label="操作" min-width="200" fixed="right" align="center">-->
      <!--        <template #default="scope">-->
      <!--          <el-button-->
      <!--            link-->
      <!--            type="primary"-->
      <!--            @click="handlePay(scope.row)"-->
      <!--            v-if="scope.row.unpaidAmount>0"-->
      <!--            v-hasPermi="['dispatch:payment:update']"-->
      <!--          >-->
      <!--            确认付款-->
      <!--          </el-button>-->

      <!--          <el-button-->
      <!--            link-->
      <!--            type="warning"-->
      <!--            @click="cancelPay(scope.row.id)"-->
      <!--            v-hasPermi="['dispatch:payment:update']"-->
      <!--            v-if="scope.row.payStatus != 1"-->
      <!--          >-->
      <!--            撤销付款-->
      <!--          </el-button>-->

      <!--          <el-button-->
      <!--            link-->
      <!--            type="danger"-->
      <!--            @click="handleDelete(scope.row.id)"-->
      <!--            v-hasPermi="['dispatch:payment:delete']"-->
      <!--            v-if="scope.row.payStatus ==1"-->
      <!--          >-->
      <!--            驳回-->
      <!--          </el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      :page-sizes="pageSizes"
    />
  </ContentWrap>

  <el-dialog
    v-model="dialogPayVisible"
    title="确认付款"
    width="20%"
  >
    <el-input v-model="handlePayData.payAmount"/>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogPayVisible = false">取消</el-button>
        <el-button type="primary" @click="comfirmPay"
        >付款</el-button
        >
      </span>
    </template>
  </el-dialog>


  <!-- 表单弹窗：添加/修改 -->
  <PaymentForm ref="formRef" @success="getList"/>
</template>

<script setup lang="ts">
import {DICT_TYPE} from '@/utils/dict'
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {PaymentApi, PaymentVO} from '@/api/dispatch/payment'
import PaymentForm from './PaymentForm.vue'
import {ElLoading, ElMessage} from "element-plus";
import {string} from "vue-types";
import {erpPriceInputFormatter, getSumValue} from "@/utils";
import {StoreApi, StoreVO} from "@/api/dispatch/store";

/** 付款单 列表 */
defineOptions({name: 'DispatchPayment'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const storeList = ref<StoreVO[]>([])

const pageSizes = ref([10, 20, 50, 100, 10000])

const loading = ref(true) // 列表的加载中
const dialogPayVisible = ref(false) // 列表的加载中
const list = ref<PaymentVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数


const popoverVisible = ref();

const multipleTableRef = ref()
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const getSummaries = (param) => {
  const {columns, data} = param
  const sums: string[] = []
  columns.forEach((column, index: number) => {
    if (['dispatchPrice'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumDispatchPrice.value);
    } else if (['paidAmount'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumPaidAmount.value);
    } else if (['unpaidAmount'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumUnpaidAmount.value);
    } else {
      sums[index] = ''
    }
  })
  return sums
}

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  ids: [],
  licensePlate: undefined,
  carType: undefined,
  payDate: [],
})

const handlePayData = reactive({
  id: undefined,
  payAmount: undefined
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中


const sumDispatchPrice = ref(0);
const sumPaidAmount = ref(0);
const sumUnpaidAmount = ref(0);
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PaymentApi.getPaymentPage(queryParams)
    if (data == null) {
      list.value = [];
      total.value = 0;
      sumDispatchPrice.value = 0;
      sumPaidAmount.value = 0;
      sumUnpaidAmount.value = 0;
      return;
    }
    let page = data.page;
    list.value = page.list;
    total.value = page.total;

    let statistics = data.statistics;
    sumDispatchPrice.value = statistics.sumDispatchPrice;
    sumPaidAmount.value = statistics.sumPaidAmount;
    sumUnpaidAmount.value = statistics.sumUnpaidAmount;

  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.ids = [];
  handleQuery()
}


/**
 * 批量驳回
 */
const handleBatchReject = async () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择要驳回的订单');
    return;
  }
  let loading;
  try {

    await message.delConfirm('是否确认批量驳回付款单？', '驳回付款单')

    loading = ElLoading.service({
      lock: true,
      text: '驳回中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    await PaymentApi.batchReject(multipleSelection.value)
    message.success(t('处理成功'))
    // 刷新列表
    await getList()
  } catch {

  } finally {
    multipleTableRef.value!.clearSelection()
    loading.close()
  }
}
const openPopoverVisible = async (id) => {
  // if (popoverVisible.value == null) {
  popoverVisible.value = id;
  // } else {
  //   popoverVisible.value = null;
  // }
}
const closePopover = async () => {
  popoverVisible.value = null;
}
const handleRightClick = (id) => {
  popoverVisible.value = id;
};

/**
 * 批量付款
 */
const handleBatchlPay = async () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择要付款的订单');
    return;
  }
  let loading;
  try {

    await message.delConfirm('是否确认批量付款？', '批量付款')

    loading = ElLoading.service({
      lock: true,
      text: '批量付款中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    await PaymentApi.handleBatchPay(multipleSelection.value)
    message.success(t('处理成功'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    multipleTableRef.value!.clearSelection()
    loading.close()
    popoverVisible.value = null;
  }
}


/**
 * 批量撤销对账
 */
const handleBatchCancelReconciliation = async () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择要撤销对账的订单');
    return;
  }
  let loading;
  try {

    await message.confirm('是否确认批量撤销对账？', '批量撤销对账')

    loading = ElLoading.service({
      lock: true,
      text: '撤销对账中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    await PaymentApi.handleBatchCancelReconciliation(multipleSelection.value)
    message.success(t('处理成功'))
    await getList()
  } catch {
  } finally {
    multipleTableRef.value!.clearSelection()
    loading.close()
    popoverVisible.value = null;
  }
}

/**
 * 批量对账
 */
const handleBatchReconciliation = async () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择要对账的订单');
    return;
  }
  let loading;
  try {

    await message.confirm('是否确认批量对账？', '批量对账')

    loading = ElLoading.service({
      lock: true,
      text: '批量对账中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    await PaymentApi.handleBatchReconciliation(multipleSelection.value)
    message.success(t('处理成功'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    multipleTableRef.value!.clearSelection()
    loading.close()
    popoverVisible.value = null;
  }
}

/**
 * 批量撤销付款
 */
const handleBatchCancelPay = async () => {

  if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择要撤销的订单');
    return;
  }
  let loading;
  try {

    await message.delConfirm('是否确认批量撤销付款？', '撤销付款')

    loading = ElLoading.service({
      lock: true,
      text: '撤销付款中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })

    await PaymentApi.batchCancelPay(multipleSelection.value)
    message.success(t('处理成功'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    multipleTableRef.value!.clearSelection()
    loading.close()
    popoverVisible.value = null;
  }
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm('是否确认驳回该付款单？', '驳回付款单')
    // 发起删除
    await PaymentApi.deletePayment(id)
    message.success(t('驳回成功'))
    // 刷新列表
    await getList()
  } catch {
  } finally {
    popoverVisible.value = null;
  }
}

const comfirmPay = async () => {
  try {
    // 确认付款的二次确认
    await message.confirm('是否确认付款？', '确认付款')
    // 发起确认付款
    await PaymentApi.handlePay(handlePayData)
    message.success(t('确认付款成功'))
    // 刷新列表
    await getList()
    dialogPayVisible.value = false;
  } catch {
  } finally {
    popoverVisible.value = null;
  }
}

// 撤销对账
const handleCancelCheck = async (id) => {
  try {
    await message.confirm('是否确认撤销对账？', '撤销对账')

    loading.value = true

    await PaymentApi.cancelCheck(id)
    message.success(t('撤销成功'))
    await getList()
  } catch {
  } finally {
    loading.value = false
    popoverVisible.value = null;
  }
}

// 撤销付款
const cancelPay = async (id) => {
  try {
    await message.confirm('是否确认撤销付款？', '撤销付款')
    await PaymentApi.cancelPay(id)
    message.success(t('撤销成功'))
    await getList()
  } catch {
  } finally {
    popoverVisible.value = null;
  }
}

/** 确认付款按钮操作 */
const handlePay = async (row) => {

  if (row.unpaidAmount == 0) {
    message.error('该付款单已全部付款')
    return;
  }

  dialogPayVisible.value = true;
  handlePayData.id = row.id;
  handlePayData.payAmount = row.unpaidAmount;//未付款金额
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PaymentApi.exportPayment(queryParams)
    download.excel(data, '付款单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const route = useRoute();
/** 初始化 **/
onMounted(async () => {

//初始化ids
  queryParams.ids = null;

  let query = route.query;
  if (query.doType == 'query') {
    queryParams.ids = query.data;
  }

  storeList.value = await StoreApi.getStoreSimpleList();
  // getList()
})
onActivated(() => {

  //初始化ids
  queryParams.ids = null;

  let query = route.query;
  if (query.doType == 'query') {
    queryParams.ids = query.data;
  }

  popoverVisible.value = null;
  getList()
})
</script>
